import { defineStore } from 'pinia';
import { setCache, getCache } from '@/utils/cache';
import { TOKEN_KEY, USER_INFO_KEY } from '@/enums/cacheEnum';
import { getUserInfo } from '@/services/api/user';
import { useAuthStore } from './auth';
import { useRequest } from 'alova';

interface UserState {
	user ?: UserModel;
}
const { send: sendGetUserInfo } = useRequest(getUserInfo, { immediate: false });

export const useUserStore = defineStore({
	id: 'user',
	state: () : UserState => ({
		user: undefined,
	}),
	getters: {
		getUser: (state) => state.user,
	},
	actions: {
		initUser() {
			const token = getCache<string>(TOKEN_KEY) || undefined;
			if (!token) {
				return;
			}
			this.initUserInfo();
		},
		setUser(user : UserModel | undefined) {
			setCache(USER_INFO_KEY, user);
			this.user = user;
		},
		/**
		 * @description 初始化用户信息
		 */
		initUserInfo() {
			sendGetUserInfo().then((res) => {
				this.setUser(res);
			})
		},

	},
});